package com.webex.ta.hydra.gui.action;

import com.webex.ta.hydra.clipboard.ClipBoard;
import com.webex.ta.hydra.core.Command;
import com.webex.ta.hydra.gui.GuiPackage;
import com.webex.ta.hydra.gui.table.HydraTableModel;
import com.webex.ta.hydra.util.HydraUtils;

import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-7
 * Time: 9:07:41
 */
public class PasteCommandAction implements ActionHandler {
    private static Set<String> commands = new HashSet<String>();

    static {
        commands.add(ActionNames.PASTE_LINE);
    }

    public Set<String> getActionNames() {
        return commands;
    }

    public void doAction(ActionEvent e) {
        Vector<Command> copied = ClipBoard.getInstance().getContents();
        if (copied != null && copied.size() > 0) {
            // filter out the children
            for (int i = 0; i < copied.size(); i ++) {
                for (int j = copied.size() - 1; j > i; j--) {
                    if (copied.get(j).isDescentOf(copied.get(i)))
                        copied.remove(j);
                }
            }

            GuiPackage gp = GuiPackage.getInstance();
            int row = gp.getHydraTable().getSelectedRow();
            if (row >= 0) {
                HydraTableModel tableModel = gp.getHydraTable().getModel();
                Command current = tableModel.getCommandAt(row);
                if (HydraUtils.isController(current)) {
                    InsertAction.appendChildrenTo(copied.toArray(new Command[copied.size()]), current);
//                    for (Command cmd : copied) {
//                        InsertAction.appendChildTo(cmd, current);
//                    }
                } else {
                    InsertAction.insert(copied.toArray(new Command[copied.size()]), row, false);
//                    for (Command cmd : copied)
//                        InsertAction.insert(cmd, row, false);
                }
                int newPos = tableModel.indexOf(current);
                tableModel.fireTableDataChanged();
                gp.getHydraTable().getSelectionModel().setSelectionInterval(newPos, newPos);
            } else {
                for (Command cmd : copied) {
                    InsertAction.append(cmd);
                }
            }
        }
    }
}
